package com.evan.review.ipc;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.Process;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.util.Log;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 远程服务实现
 * 运行在独立进程中，通过AIDL接口提供跨进程服务
 */
public class RemoteService extends Service {
    private static final String TAG = "RemoteService";
    
    // 消息ID计数器
    private final AtomicInteger messageIdCounter = new AtomicInteger(1);
    
    // 使用RemoteCallbackList安全地管理回调列表
    private final RemoteCallbackList<IRemoteCallback> callbackList = new RemoteCallbackList<>();
    
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "RemoteService创建，进程ID: " + Process.myPid());
    }
    
    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "RemoteService绑定");
        return binder;
    }
    
    @Override
    public boolean onUnbind(Intent intent) {
        Log.d(TAG, "RemoteService解绑");
        return super.onUnbind(intent);
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        callbackList.kill();
        Log.d(TAG, "RemoteService销毁");
    }
    
    /**
     * AIDL接口实现
     */
    private final IRemoteService.Stub binder = new IRemoteService.Stub() {
        @Override
        public int getPid() {
            return Process.myPid();
        }
        
        @Override
        public String getMessage(String prefix) {
            return prefix + " - 来自远程服务 (PID: " + Process.myPid() + ")，时间: " + System.currentTimeMillis();
        }
        
        @Override
        public MessageParcel sendMessage(MessageParcel message) {
            // 记录收到的消息
            Log.d(TAG, "收到消息: " + message.toString());
            
            // 创建响应消息
            MessageParcel response = new MessageParcel(
                    messageIdCounter.getAndIncrement(),
                    "这是对消息 #" + message.getId() + " 的回复",
                    Process.myPid()
            );
            
            // 通知所有已注册的回调
            notifyCallbacks(message);
            
            return response;
        }
        
        @Override
        public void registerCallback(IRemoteCallback callback) {
            if (callback != null) {
                callbackList.register(callback);
                Log.d(TAG, "注册回调，当前回调数: " + callbackList.getRegisteredCallbackCount());
            }
        }
        
        @Override
        public void unregisterCallback(IRemoteCallback callback) {
            if (callback != null) {
                callbackList.unregister(callback);
                Log.d(TAG, "注销回调，当前回调数: " + callbackList.getRegisteredCallbackCount());
            }
        }
    };
    
    /**
     * 通知所有已注册的回调
     */
    private void notifyCallbacks(MessageParcel message) {
        final int callbackCount = callbackList.beginBroadcast();
        try {
            for (int i = 0; i < callbackCount; i++) {
                try {
                    IRemoteCallback callback = callbackList.getBroadcastItem(i);
                    callback.onMessageReceived("服务端收到了您的消息: " + message.getContent());
                    callback.onParcelReceived(message);
                } catch (RemoteException e) {
                    Log.e(TAG, "通知回调失败: " + e.getMessage());
                }
            }
        } finally {
            callbackList.finishBroadcast();
        }
    }
} 